<template>
  <div class="bg-in-stock">
    <el-form ref="goodsInventoryAddForm" :model="goodsInventoryAddForm" :rules="goodsInventoryAddFormRule"
      label-width="120px" inline class="change-form">
      <h3 style="width: 100%;">盘点单</h3>
      <el-form-item label="盘点编号" prop="sn" v-if="type === 'edit' || type === 'detail'" class="change-form-item">
        <el-input v-model="goodsInventoryAddForm.sn" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="盘点时间" prop="inventory_time" class="change-form-item">
        <el-date-picker v-model="goodsInventoryAddForm.inventory_time" value-format="timestamp" type="datetime"
          :disabled="type === 'detail' || type === 'audit'" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="盘点人" prop="inventory_person_id" class="change-form-item">
        <el-select @change="forceUpdate" v-model="goodsInventoryAddForm.inventory_person_id" :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="dept_id" class="change-form-item">
        <el-cascader v-model="goodsInventoryAddForm.dept_id" :options="deptList"
          :disabled="type === 'detail' || type === 'audit'" :props="{
            label: 'name',
            value: 'id',
            emitPath: false,
            checkStrictly: true
          }" clearable @change="changewarehouseList"></el-cascader>
      </el-form-item>
      <el-form-item label="仓库" prop="warehouse_id" class="change-form-item">
        <el-select v-model="goodsInventoryAddForm.warehouse_id" @change="handleChangeWareHouse"
          :disabled="type === 'detail' || type === 'audit'">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="制单人" prop="creator_id" class="change-form-item">
        <el-select
          v-model="goodsInventoryAddForm.creator_id"
          :disabled="type === 'detail' || type === 'audit'"
          @change="forceUpdate">
          <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <div class="mx">
        <h3>商品明细</h3>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'detail'"
          @click="handleSelectWarehouseEntryBatch">选择</el-button>
      </div>
      <div style="width: 100%; display: block;">
        <el-form-item style="width: 100%;">
          <el-table :data="goodsInventoryAddForm.product_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="入库单号">
              <template slot-scope="scope">
                {{ scope.row.warehouse_entry_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品编号">
              <template slot-scope="scope">
                {{ scope.row.product_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.product_name }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号">
              <template slot-scope="scope">
                {{ scope.row.product_specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位">
              <template slot-scope="scope">
                {{ scope.row.product_unit }}
              </template>
            </el-table-column>
            <el-table-column label="库存数量">
              <template slot-scope="scope">
                {{ scope.row.remain_num }}
              </template>
            </el-table-column>
            <el-table-column label="盘点数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.inventory_num" type="number" :min="0" :maxlength="20"
                  :disabled="type === 'detail' || type === 'audit'"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="差异">
              <template slot-scope="scope">
                {{ scope.row.inventory_num - scope.row.remain_num || 0 }}
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template slot-scope="scope">
                {{ scope.row.remark }}
                <el-input v-model="scope.row.remark" :min="0" :maxlength="20" :disabled="true" v-show="false"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="type !== 'detail' && type !== 'audit'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="goodsInventoryAddForm.product_list.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <el-button v-if="type === 'audit' && type !== 'detail'" type="primary" @click="handlePassGoodsInventory()">审核通过
      </el-button>
      <el-button v-if="type === 'audit' && type !== 'detail'" type="danger" @click="dialogVisible = true">审核驳回
      </el-button>
      <el-button v-if="type !== 'audit' && type !== 'detail'" type="primary" @click="submitGoodsInventoryAddForm">保存
      </el-button>
      <el-button @click="$router.back()">返回
      </el-button>
    </div>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form ref="goodsInventoryAddForm" :model="goodsInventoryAddForm" label-width="120px" inline style="width:900px">
        <el-form-item label="驳回原因" prop="reject_reason" required="true">
          <el-input v-model="goodsInventoryAddForm.reject_reason" type="textarea" :minlength="0"
            :maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectGoodsInventory()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Foundation, RegExp } from '~/ui-utils'
import * as API_GoodsInventory from '@/api/goodsInventory'
import * as API_Setting from '@/api/setting'
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_Erp from '@/api/erp'
import * as API_Auth from '@/api/auth'
export default {
  name: 'goodsInventoryAdd',
  data() {
    return {
      adminList: [],
      dialogVisible: false,
      warehouseList: [],
      deptList: [],
      deptListAll: [],
      id: '',
      type: '',
      /** 出库单表单*/
      goodsInventoryAddForm: {
        product_list: []
      },
      /** 校验规则 */
      goodsInventoryAddFormRule: {
        inventory_person_id: { required: true, message: '请选择盘点人', trigger: 'change' },
        warehouse_id: { required: true, message: '请选择报仓库', trigger: 'change' },
        dept_id: { required: true, message: '请选择所属部门', trigger: 'change' },
        creator_id: { required: true, message: '请选择制单人', trigger: 'change' }
      },
      warehouseProduct: null
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  mounted() {
    if (this.$route.name === 'goodsInventoryEdit') {
      this.type = 'edit'
    } else if (this.$route.name === 'goodsInventoryAudit') {
      this.type = 'audit'
    } else if (this.$route.name === 'goodsInventoryReturn') {
      this.type = 'return'
    } else if (this.$route.name === 'goodsInventoryAdd') {
      this.goodsInventoryAddForm.creator_id = this.user.uid
      this.goodsInventoryAddForm.inventory_person_id = this.user.uid
      this.goodsInventoryAddForm.dept_id = this.user.dept_id
      this.GET_WarehouseList({ dept_id: this.user.dept_id })
      this.$set(this.goodsInventoryAddForm, 'inventory_time', new Date().getTime())
    } else if (this.$route.name === 'goodsInventoryDetail') {
      this.type = 'detail'
    }
    if (this.$route.params.id) {
      this.id = this.$route.params.id
      this.GET_goodsInventoryAddDetail()
    }
    this.GET_AdministratorList()
    this.GET_DeptList()
  },
  methods: {
    /** 修改报单人 */
    forceUpdate() {
      this.$forceUpdate()
    },
    /** 清除已选商品明细 */
    cleanGoodsList() {
      // 切换部门或仓库需要清除已选对应仓库下的商品数据
      this.goodsInventoryAddForm.product_list = []
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    /** 审核-通过 */
    handlePassGoodsInventory() {
      this.$confirm('确定通过吗？', '提示', { type: 'warning' }).then(() => {
        // const ids = this.multipleSelection.map(item => item.id)
        API_GoodsInventory.auditGoodsInventory(this.id, { status: 'PASS' }).then(() => {
          this.$message.success('已通过！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'goodsInventory' })
        })
      }).catch(() => { })
    },
    /** 审核-拒绝 */
    handleRejectGoodsInventory() {
      if (!this.goodsInventoryAddForm.reject_reason) {
        this.$message.error('请填写驳回原因！')
        return
      }
      this.$confirm('确定拒绝吗？', '提示', { type: 'warning' }).then(() => {
        // const ids = this.multipleSelection.map(item => item.id)
        API_GoodsInventory.auditGoodsInventory(this.id, { status: 'REJECT', reject_reason: this.goodsInventoryAddForm.reject_reason }).then(() => {
          this.$message.success('已拒绝！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'goodsInventory' })
        })
      }).catch(() => { })
    },
    changewarehouseList(e) {
      this.$set(this.goodsInventoryAddForm, 'warehouse_id', '')
      this.GET_WarehouseList({ dept_id: e })
      this.cleanGoodsList()
    },
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll(e).then(response => {
        this.warehouseList = response
      })
    },
    submitGoodsInventoryAddForm() {
      this.$refs['goodsInventoryAddForm'].validate(valid => {
        if (valid) {
          const { id } = this.goodsInventoryAddForm
          const params = this.MixinClone(this.goodsInventoryAddForm)
          if (params.dept_id) {
            params.dept_name = this.deptListAll.find(dept => dept.id === params.dept_id).name
          }
          if (params.warehouse_id) {
            params.warehouse_name = this.warehouseList.find(ware => ware.id === params.warehouse_id).name
          }
          if (params.creator_id) {
            params.creator = this.adminList.find(admin => admin.id === params.creator_id).real_name
          }
          if (params.inventory_person_id) {
            params.inventory_person = this.adminList.find(admin => admin.id === params.inventory_person_id).real_name
          }
          params.inventory_time = Math.floor(params.inventory_time / 1000)
          params.product_list = params.product_list.map(item => {
            const query = {
              diff_num: item.inventory_num - item.remain_num,
              inventory_num: item.inventory_num * 1,
              product_id: item.product_id,
              product_name: item.product_name,
              product_sn: item.product_sn,
              specification: item.product_specification,
              stock_num: item.remain_num * 1,
              unit: item.product_unit,
              goods_id: item.goods_id,
              remark: item.remark
            }
            return query
          })
          if (id) {
            API_GoodsInventory.editgoodsInventoryAdd(id, params).then(response => {
              this.$message.success('修改成功！')
              const { callback } = this.$route.params
              if (typeof callback === 'function') callback()
              this.$store.dispatch('delCurrentViews', {
                view: this.$route,
                $router: this.$router
              })
              this.$router.push({ name: 'goodsInventory' })
            })
          } else {
            API_GoodsInventory.addgoodsInventoryAdd(params).then(() => {
              this.$message.success('添加成功！')
              const { callback } = this.$route.params
              if (typeof callback === 'function') callback()
              this.$store.dispatch('delCurrentViews', {
                view: this.$route,
                $router: this.$router
              })
              this.$router.push({ name: 'goodsInventory' })
            })
          }
        }
      })
    },
    // 选择出库单
    async handleSelectWarehouseEntryBatch() {
      if (!this.goodsInventoryAddForm.warehouse_id) {
        this.$message.error('请先选择仓库！')
        return
      }
      const goodsData = await this.$EnwarehouseEntryBatch({
        goodsApi: 'admin/erp/warehouseEntryBatch',
        warehouseList: this.warehouseList,
        selectedIds: this.id ? this.goodsInventoryAddForm.product_list && this.goodsInventoryAddForm.product_list.map(item => item.id) : this.goodsInventoryAddForm.product_list.map(item => item.id),
        purchasePlanApiParams: { warehouse_id: this.goodsInventoryAddForm.warehouse_id }
      })
      this.goodsInventoryAddForm.warehouse_id = goodsData.warehouse_id
      let ProductLendNum = goodsData.purchasePlans.map(item => {
        const query = {
          product_id: item.product_id,
          stock_sn: item.warehouse_entry_sn
        }
        return query
      })
      this.getlistProductLendNum(ProductLendNum, goodsData.purchasePlans)
    },
    getlistProductLendNum(ProductLendNumList, warehouseEntryBatch) {
      API_GoodsInventory.getlistProductLendNum(ProductLendNumList).then(response => {
        warehouseEntryBatch.map(item => {
          response.forEach(item2 => {
            if (item.product_id === item2.product_id && item.warehouse_entry_sn === item2.stock_sn) {
              item.remark = item2.lend_num ? '借出' + item2.lend_num + (item.product_unit ? item.product_unit : '') : ''
            }
          })
        })
        this.goodsInventoryAddForm.product_list = warehouseEntryBatch
      })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
        this.deptListAll = response
      })
    },
    /** 切换仓库 */
    handleChangeWareHouse(val) {
      this.goodsInventoryAddForm.product_list = []
    },
    /** 获取详情页面数据 */
    GET_goodsInventoryAddDetail() {
      API_GoodsInventory.getGoodsInventoryInfo(this.id).then(response => {
        this.goodsInventoryAddForm = response
        this.GET_WarehouseList({ dept_id: response.dept_id })
        this.goodsInventoryAddForm.inventory_time = Math.floor(this.goodsInventoryAddForm.inventory_time * 1000)
        this.goodsInventoryAddForm.distribution_name = response.staff_name
        this.goodsInventoryAddForm.product_list = this.goodsInventoryAddForm.product_list.map(item => {
          item.product_specification = item.specification
          item.product_unit = item.unit
          item.remain_num = item.stock_num
          return item
        })
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;
  width: 100%;

  .button {
    margin-left: 10px;
  }
}

.change-form {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  min-width: 900px;

  .change-form-item {
    width: 30%;
    margin: 0 10px 20px 0;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
  }

  /deep/ {
    .el-form-item__content {
      flex: 1;
      width: 100%;
    }

    .el-date-editor,
    .el-cascader,
    .el-select {
      width: 100%;
    }
  }
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

/deep/ {
  .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}
</style>
